#
# Copyright (C) 2011
#
# Brick Yang <printfxxx@163.com>
#
# This program is free software. You can redistribute it and/or
# modify it as you like.
#

##
# File		rule.mk
# Brief		Rules in each directories.
#

SHELL = $(BASH)
include $(topdir)func.mk

# Extract nodes recursively
define extract_node
$(foreach f,$(1),$(if $($(f)),$(f) $(call extract_node,$($(f)))))
endef
# Extract leafs recursively
define extract_leaf
$(foreach f,$(1),$(if $($(f)),$(call extract_leaf,$($(f))),$(f)))
endef
# Copy file to optdir
define copy_to_opt
all: $$(optdir)$(3)

$$(optdir)$(3): $(1)$(2)
	$$(call msg,COPY,$(3))
	cp $$< $$@ -a
endef
# install file
define install
install: $(3)$(4)

$(3)$(4): $(1)$(2)
	$$(call msg,INSTALL,$(4))
	install -d $(3)
	install -m $(5) $$< $$@
endef

bdir = .build/

bindir     ?= /usr/bin
libdir     ?= /usr/lib
datadir    ?= /usr/share
includedir ?= /usr/include
sysconfdir ?= /etc

BUILD_CMD = all install

EXTR_SEG := V
include $(EXTR_LIST)
EXTR_SEG :=

include Makefile

_obj = $(obj) $(obj-y)
NODE = $(call extract_node,$(_obj))
LEAF = $(call extract_leaf,$(_obj))
MOD  = $(filter-out %/,$(NODE))
DIR  = $(filter %/,$(LEAF))
TGT  = $(filter-out %/,$(LEAF))

ifneq ($(filter $(BUILD_CMD),$(MAKECMDGOALS)),)
$(shell mkdir -p $(addprefix $(bdir),$(sort $(dir $(MOD) $(TGT)) ./)))
endif

$(foreach f,$(MOD),$(eval dirs_$(f) = $(filter %/,$($(f)))))
$(foreach f,$(MOD),$(eval tgts_$(f) = $(filter-out %/,$($(f)))))
$(foreach f,$(MOD),$(eval $(bdir)$(f): $(tgts_$(f):%=$(bdir)%)))

$(DIR:%/=build-%): build-%:
	$(call msg2,CD,$*/)
	$(MAKE) -f $(topdir)rule.mk -C $*/ all

$(DIR:%/=install-%): install-%:
	$(call msg2,CD,$*/)
	$(MAKE) -f $(topdir)rule.mk -C $*/ install

all: $(MOD:%=$(bdir)%) $(DIR:%/=build-%)

install: $(DIR:%/=install-%)

FORCE:

EXTR_SEG := R
include $(EXTR_LIST)
EXTR_SEG :=

.PHONY: FORCE all install $(DIR:%/=build-%) $(DIR:%/=install-%)
